<?php
namespace app\api\models;

use app\api\core\CreateUuid;
use app\api\core\MP3File;
use app\api\core\wechat\wxAction;
use phpDocumentor\Reflection\DocBlock\Tags\Var_;
use yii\base\Model;
use \Cm;
use Yii;
use yii\helpers\ArrayHelper;
use yii\helpers\VarDumper;
use yii\log\EmailTarget;
use yii\web\UploadedFile;
use yii\widgets\Breadcrumbs;

class MaterialModel extends BaseModel
{
    public function actionTempList()
    {
        $type = Cm::$req->post('type',['reg'=>'/^[a-z]+/', 'title'=>'素材类型']);
        $page = (int)Cm::$req->post('page',['reg'=>'/^\d+/', 'title'=>'分页']);
        $page_size = (int)Cm::$req->post('page_size',['reg'=>'/^\d+/', 'title'=>'素材个数', 'null','empty', 'default'=>'5']);
        $groupIds = Cm::$req->post('group_id', ['reg'=>'/^[0-9A-Za-z]{1,}/', 'title'=>'分组', 'null','empty']);

        if (!in_array($type, ['image', 'video','voice'])) {
            Cm::$res->error('素材类型不符合规则');
        }

        $where = '';
        if (!empty($groupIds)) {
            $where = " and group_id='{$groupIds}'";
        }

        $sql = "
        SELECT id,title,media_id,add_time,update_time,url,group_id 
        FROM `scrm_weixin_fover_material`  
        WHERE wx_account_id='{$this->wx_account_id}' and `type`='{$type}' and `status`=0  {$where}
        ORDER BY add_time desc ";
        $result = Cm::$db->paging($sql, $page, $page_size);

        $result['wx_account_id'] = $this->wx_account_id;
        $result['appid'] = $this->wx_app_id;
        $result['company_id'] = $this->company_id;
        $result['type'] = $type;

        Cm::$res->susess('success', $result);
    }

    public function actionTempGroupList()
    {
        $type = Cm::$req->post('type',['reg'=>'/^[a-z]+/', 'title'=>'素材类型']);


        $list = Cm::$db->all("SELECT (0) as num, id, name group_name FROM scrm_weixin_fover_material_group WHERE wx_account_id='{$this->wx_account_id}'");
        $sql = "SELECT count(*) num, g.id, IFNULL(g.name, '未分组') as `group_name`
        FROM `scrm_weixin_fover_material` as m  
        LEFT JOIN scrm_weixin_fover_material_group as g on g.id=m.group_id  
        WHERE m.wx_account_id='{$this->wx_account_id}' and m.`type`='{$type}' and m.status=0
        GROUP BY g.id ";
        $resultItems = Cm::$db->all($sql);



        $types = ['image'=>'图片', 'video'=>'视频','voice'=>'语音'];
        if ($resultItems) {
            $count = (int)array_sum($this->_array_column($resultItems, 'num'));
            array_unshift($resultItems, [
                'num'=>$count,
                'group_name'=>'全部'.$types[$type],
                'group_id'=>null
            ]);
        } else {
            $resultItems = [];
        }
        $result = [
            'data'=>array_values($this->people($resultItems, $list, 'group_name')),
            'type'=>$type
        ];
        Cm::$res->susess('success', $result);
    }

    /* @return array $people 数组 * */
    function people($arr1,$arr2, $key='group_name'){
        $sql=array_merge($arr1, $arr2);
        $res = array();
        foreach ($sql as $value) {
            if(isset($res[$value[$key]])) {
                unset($value[$key]);
            } else { $res[$value[$key]] = $value;
            }
        }
        $people=array();
        foreach($res as $key=>$value){
            $people[]=$value;
        } return $people;
    }


    public function actionTempListNum()
    {
        $appid = Cm::$req->post('appid', ['reg'=>'/^[0-9A-Za-z]{1,}/', 'title'=>'微信公总号APPID']);

        $wechat=  new wxAction($appid);
        $sql= "select *from `scrm_weixin_fover_material_count` where wx_account_id='{$wechat->wx_app_data_id}'";
        $count = Cm::$db->one($sql);

        if ($count && $count['update_time'] > time()) {
            $wxCount =[
                'voice_count'=>$count['voice_count'],
                'video_count'=>$count['video_count'],
                'image_count'=>$count['image_count'],
                'news_count'=>$count['news_count'],
            ];
        } else {
            $wxCount = $wechat->getForeverCount();
            if (!$wxCount) {
                return false;
            } else {
                $dataCount = [
                    // 'wx_account_id'=>$wechat->wx_app_data_id,
                    'voice_count'=>$wxCount['voice_count'],
                    'video_count'=>$wxCount['video_count'],
                    'image_count'=>$wxCount['image_count'],
                    'news_count'=>$wxCount['news_count'],
                    //'update_time'=>'',
                ];
                if ($count) {
                    Cm::$db->update('scrm_weixin_fover_material_count', $dataCount, "wx_account_id='{$wechat->wx_app_data_id}'");
                } else {
                    $dataCount['id'] = (new CreateUuid())->toString();
                    $dataCount['update_time'] = time()+24*3600;
                    $dataCount['wx_account_id'] = $wechat->wx_app_data_id;
                    Cm::$db->insert('scrm_weixin_fover_material_count', $dataCount);
                }
            }
        }

        if ($wxCount) {
            Cm::$res->susess('success',$wxCount);
        } else {
            Cm::$res->error(!empty($wechat->error) ? $wechat->error : $wechat->errMsg);
        }
    }

    public function actionTempDel()
    {
        $appid = Cm::$req->post('appid', ['reg'=>'/^[0-9A-Za-z]{1,}/', 'title'=>'微信公总号APPID']);
        $id = Cm::$req->post('id', ['reg'=>'/^[0-9A-Za-z]{1,}/', 'title'=>'消息ID']);

        $data = Cm::$db->one("SELECT id, media_id,type FROM scrm_weixin_fover_material where id='{$id}' and wx_account_id='{$this->wx_account_id}'");
        if (!$data) {
            Cm::$res->error('素材不存在！');
        }

        $media_id = $data['media_id'];
        $type = $data['type'];
        $wechat=  new wxAction($appid);

        $result = $wechat->delForeverMedia($media_id);
        if ($result) {
            Cm::$db->delete('scrm_weixin_fover_material', "id='{$id}'");
            if ($type === 'news') {
                Cm::$db->delete('scrm_weixin_fover_material_items', "material_id='{$id}'");
            }
            Cm::$res->susess('删除素材成功！');
        } else {
            if (!empty($wechat->errCode)  && ($wechat->errCode=='48005' || $wechat->errCode==48005)) {
                $msg = '禁止删除被自动回复和自定义菜单引用的素材';
            } else {
                $msg = !empty($wechat->error) ? $wechat->error : $wechat->errMsg;
            }
            Cm::$res->error(!empty($wechat->error) ? $wechat->error : $wechat->errMsg, ['code'=>$wechat->errCode]);
        }
    }

    /**
     * 批量删除
     */
    public function actionTempBatchDel()
    {
        $ids = Cm::$req->post('id', ['reg'=>'/^[0-9A-Za-z,]{1,}/', 'title'=>'消息ID']);

        $itemIds = implode(',',  array_map(function ($v){ return "'{$v}'";}, explode(',', str_replace('，',',', $ids)))) ;

        Cm::$db->update('', [
            'status'=>1,
            'del_time'=>date('Y-m-d H:i:s')
        ], "id in ({$itemIds})");

        Cm::$res->susess('删除成功！');
    }


    public function actionTempAdd()
    {
        $appid = Cm::$req->post('appid', ['reg'=>'/^[0-9A-Za-z]{1,}/', 'title'=>'微信公总号APPID']);
        $type = Cm::$req->post('type', ['reg'=>'/^\w+/', 'title'=>'素材类型']);

        if (!in_array($type, ['image','voice','video','thumb'])) {
            Cm::$res->error('素材类型不符合规则');
        }

        $title = Cm::$req->post('title', ['title'=>'视频素材标题','null', 'empty']);
        $introduction = Cm::$req->post('intro', ['title'=>'视频素材描述', 'null', 'empty']);
        if ($type=='video') {
            if (!($title && $introduction)) {
                Cm::$res->error('上传视频素材必须要视频标题，视频描述');
            }
        }

        $upload = UploadedFile::getInstanceByName('file');
        if (!$upload) {
            Cm::$res->error('请传递素材文件或文件标记为：file');
        }
        $suffix = strtolower($upload->getExtension());
        $size = $this->sizeToMB($upload->size);#MB
        $video = false;
        switch ($type) {
            case 'image':#图片
                //bmp/png/jpeg/jpg/gif
                if (!in_array($suffix, ['bmp', 'png', 'jpeg', 'jpg', 'gif'])) {
                    Cm::$res->error('素材图片类型不符合');
                }

                if ($size > 2) {
                    Cm::$res->error('素材图片太大');
                }
                break;
            case 'voice':#语音
                //mp3/wma/wav/amr
                if (!in_array($suffix, ['mp3', 'wma', 'wav', 'amr'])) {
                    Cm::$res->error('素材语音类型不符合');
                }

                if ($size > 2) {
                    Cm::$res->error('素材语音太大');
                }

                //分析mp3文件
                $mp3 = new \getID3();
                $mp = $mp3->Analyze($upload->tempName);
                if (isset($mp['playtime_seconds']) && $mp['playtime_seconds'] > 60) {
                    Cm::$res->error('素材语音播放时长只能是60秒内');
                }

                break;
            case 'video':#视频
                if (!in_array($suffix, ['mp4'])) {
                    Cm::$res->error('素材视频类型不符合');
                }

                if ($size > 10) {
                    Cm::$res->error('素材视频太大');
                }
//分析mp3文件
//                $mp4 = new \getID3();
//                $mp = $mp4->Analyze($upload->tempName);
//                var_dump($mp);exit;
//                if (isset($mp['playtime_seconds']) && $mp['playtime_seconds'] > 60) {
//                    Cm::$res->error('素材语音播放时长只能是60秒内');
//                }
                $video = true;
                break;
            case 'thumb':#其他缩略图
                if (!in_array($suffix, ['jpg'])) {
                    Cm::$res->error('素材缩略图类型不符合');
                }

                if ($size > 64) {
                    Cm::$res->error('素材缩略图太大');
                }
                break;
            default:
                Cm::$res->error('你上传的文件不符合要求');
                break;
        }

        $dir = './upload/'; //rtrim(Yii::getAlias('@upload'), '/').'/';

        if (!is_dir($dir)) {
            mkdir($dir, 0777);
        }
        $fileName = $this->msectime().'.'.$suffix;
        $filePathName = $dir.$this->msectime().'.'.$suffix;


        $result = $upload->saveAs($filePathName);

        if (!$result) {
            Cm::$res->error($upload->getHasError());
        }

        if (class_exists ( '\CURLFile' )) {//关键是判断curlfile,官网推荐php5.5或更高的版本使用curlfile来实例文件
            $filedata =[
                'media' => new \CURLFile ( realpath ( $filePathName ), $upload->type )
            ];
        } else {
            $filedata =[
                'media' => '@' . realpath ( $filePathName )
            ];
        }
        $videoInfo = [
            'title'=>$title,
            'introduction'=>$introduction,
        ];
        $wechat=  new wxAction($appid);
        $wechatResult = $wechat->uploadForeverMedia($filedata, $type, $video, $videoInfo);

        //删除文件
        //unlink($filePathName);
        if ($wechatResult) {
            $materialId = (new CreateUuid())->toString();
            if ($type==='thumb') {
                $item = [
                    'id'=>$materialId,
                    'wx_account_id'=>$this->wx_account_id,
                    'add_time'=>date('Y-m-d H:i:s'),
                    'update_time'=>date('Y-m-d H:i:s'),
                    'type'=>$type,
                    'title'=>$fileName,
                    'media_id'=>$wechatResult['media_id'],
                    'url'=>$wechatResult['url'],
                ];
                Cm::$db->insert('scrm_weixin_fover_material', $item);
            } else {
                $start = Cm::$db->one("SELECT {$type}_start FROM `scrm_weixin_fover_material` WHERE wx_account_id='{$this->wx_account_id}' and type='{$type}' ORDER BY add_time desc ");
                //'image','voice','video','thumb'
                $dataItems= [];
                switch ($type) {
                    case 'image':
                        $dataItems = [
                            'id'=>$materialId,
                            'wx_account_id'=>$this->wx_account_id,
                            'add_time'=>date('Y-m-d H:i:s'),
                            'update_time'=>date('Y-m-d H:i:s'),
                            'type'=>$type,
                            "{$type}_start"=>isset($start[$type.'_start']) && !empty($start[$type.'_start']) ? $start[$type.'_start'] : 1,
                            'title'=>$fileName,
                            'media_id'=>$wechatResult['media_id'],
                            'url'=>$wechatResult['url'],
                        ];
                        break;
                    case 'voice':
                        $dataItems = [
                            'id'=>$materialId,
                            'wx_account_id'=>$this->wx_account_id,
                            'add_time'=>date('Y-m-d H:i:s'),
                            'update_time'=>date('Y-m-d H:i:s'),
                            'type'=>$type,
                            "{$type}_start"=>isset($start[$type.'_start']) && !empty($start[$type.'_start']) ? $start[$type.'_start'] : 1,
                            'title'=>$fileName,
                            'media_id'=>$wechatResult['media_id'],
                            //'url'=>$wechatResult['url'],
                        ];
                        break;
                    case 'video':
                        $dataItems = [
                            'id'=>$materialId,
                            'wx_account_id'=>$this->wx_account_id,
                            'add_time'=>date('Y-m-d H:i:s'),
                            'update_time'=>date('Y-m-d H:i:s'),
                            'type'=>$type,
                            "{$type}_start"=>isset($start[$type.'_start']) && !empty($start[$type.'_start']) ? $start[$type.'_start'] : 1,
                            'title'=>$title,
                            'intro'=>$introduction,
                            'media_id'=>$wechatResult['media_id'],
                            //'url'=>$wechatResult['url'],
                        ];
                        break;
                }
                if (!empty($dataItems)) {
                    Cm::$db->insert('scrm_weixin_fover_material', $dataItems);
                }
            }

            $wechatResult['id'] = $materialId;
            Cm::$res->susess('success', $wechatResult);
        } else {
            Cm::$res->error(!empty($wechat->errMsg) ? $wechat->errMsg : '上传失败');
        }
    }

    /**
     * 上传图文消息内的图片获取URL
     */
    public function actionTempImgAdd()
    {
        $appid = Cm::$req->post('appid', ['reg'=>'/^[0-9A-Za-z]{1,}/', 'title'=>'微信公总号APPID']);

        $upload = UploadedFile::getInstanceByName('file');

        if (!$upload) {
            Cm::$res->error('请传递素材文件或文件标记为：file');
        }


        $suffix = strtolower($upload->getExtension());

        if (!in_array($suffix, ['jpg','png'])) {
            Cm::$res->error('图片类型不符合:只能是jpg/png。');
        }

        $size = $this->sizeToMB($upload->size);#MB

        if ($size > 1) {
            Cm::$res->error('图片太大：限制1M内。');
        }


        $dir = 'upload/'; //rtrim(Yii::getAlias('@upload'), '/').'/';

        $fileName = $this->msectime().'.'.$suffix;
        $filePathName = $dir.$this->msectime().'.'.$suffix;


        $result = $upload->saveAs($filePathName);

        if (!$result) {
            Cm::$res->error($upload->getHasError());
        }

        if (class_exists ( '\CURLFile' )) {//关键是判断curlfile,官网推荐php5.5或更高的版本使用curlfile来实例文件
            $filedata =[
                'media' => new \CURLFile ( realpath ( $filePathName ), $upload->type )
            ];
        } else {
            $filedata =[
                'media' => '@' . realpath ( $filePathName )
            ];
        }

        $wechat=  new wxAction($appid);

        $data = $wechat->uploadImg($filedata);

        //删除文件
        unlink($filePathName);
        if ($data) {
            $item = [
                'id'=>(new CreateUuid())->toString(),
                'wx_account_id'=>$this->wx_account_id,
                'add_time'=>date('Y-m-d H:i:s'),
                'update_time'=>date('Y-m-d H:i:s'),
                'type'=>'thumb',
                'title'=>$fileName,
                //'media_id'=>$data['media_id'],
                'url'=>$data['url'],
            ];
            Cm::$db->insert('scrm_weixin_fover_material', $item);

            Cm::$res->susess('success', $data);
        } else {
            Cm::$res->error(!empty($wechat->errMsg) ? $wechat->errMsg : '增加素材失败');
        }
    }

    public function actionArticleAdd()
    {
        $appid = Cm::$req->post('appid', ['reg'=>'/^[0-9A-Za-z]{1,}/', 'title'=>'微信公总号APPID']);
        $articles = Cm::$req->post('articles', ['reg' => '/[^,:{}\\[\\]0-9.\-+Eaeflnr-u \n\r\t]/', 'title' => '图文']);
        $verJson = $this->verJson($articles);
        if (!$verJson['flag']) {
            Cm::$res->error('无效json格式: 无效参数articles');
        }

        $arrayDepth = $verJson['dep'];

        $orderRow = $verJson['list'];

        $orderNewItems = [];
        switch ((int) $arrayDepth) {
            case 1:
                $orderNewItems[] = [
                    'title' => $orderRow['title'],
                    'thumb_media_id' => $orderRow['thumb_media_id'],
                    'show_cover_pic' => $orderRow['show_cover_pic'],
                    'content' => $orderRow['content'],
                    'content_source_url' => $orderRow['content_source_url'],
                    'author' => $orderRow['author'],
                    'digest' => $orderRow['digest'],
                ];
                break;
            case 2:
                $orderNewItems = array_map(function ($item) {
                    return [
                        'title' => $item['title'],
                        'thumb_media_id' => $item['thumb_media_id'],
                        'show_cover_pic' => $item['show_cover_pic'],
                        'content' => $item['content'],
                        'content_source_url' => $item['content_source_url'],
                        'author' => $item['author'],
                        'digest' => $item['digest'],
                    ];
                }, $orderRow);
                break;
            default:
                Cm::$res->error('无效json格式: 无效参数articles');
        }

        //开始掺入数据库：
        $data = Cm::$db->one("SELECT id, news_start,news_sync_time FROM `scrm_weixin_fover_material` where wx_account_id='{$this->wx_account_id}' and `type`='news' order by add_time desc ");

        $start = 1;
        if ($data) {
            $start = (int)$data['news_start'];
        }

        $wechat=  new wxAction($appid);

        $item = [
            'articles'=>$orderNewItems
        ];


        $result = $wechat->uploadForeverArticles($item);
        if ($result) {
            $materialId = (new CreateUuid())->toString();
            $items = [
                'media_id'=>$result['media_id'],
                'id'=>$materialId,
                'wx_account_id'=>$this->wx_account_id,
                'add_time'=>date('Y-m-d H:i:s'),
                'update_time'=>date('Y-m-d H:i:s'),
                'type'=>'news',
                "news_start"=>$start,
                'title'=>'多图文',
                'media_id'=>$result['media_id'],
                //'url'=>$wechatResult['url'],
            ];
            Cm::$db->insert('scrm_weixin_fover_material', $items);

            $items = $this->getArticle($result['media_id']);
            $listItems = [];
            if ($items) {
                $listItems = $items;
            } else {
                $listItems = $orderNewItems;
            }
            if ($listItems) {
                foreach ($listItems as $v) {
                    $row = array_filter([
                        'id'=>(new CreateUuid())->toString(),
                        'material_id'=>$materialId,
                        'title'=>$v['title'],
                        'thumb_media_id'=>$v['thumb_media_id'],
                        'show_cover_pic'=>$v['show_cover_pic'],
                        'author'=>$v['author'],
                        'digest'=>$v['digest'],
                        'content'=>$v['content'],
                        'content_source_url'=>$v['content_source_url'],
                        'url'=>isset($v['url']) ? $v['url'] : '',
                        'thumb_url'=>isset($v['thumb_url']) ? $v['thumb_url'] : '',
                        'need_open_comment'=>isset($v['need_open_comment']) ? $v['need_open_comment'] : 0,
                        'only_fans_can_comment'=>isset($v['only_fans_can_comment']) ? $v['only_fans_can_comment'] : 0,
                        'update_time'=>date('Y-m-d H:i:s'),
                        'create_time'=>date('Y-m-d H:i:s'),

                    ]);
                    Cm::$db->insert('scrm_weixin_fover_material_items', $row);
                }
            }


            $result['id'] = $materialId;
            Cm::$res->susess('success', $result);
        } else {
            Cm::$res->error(!empty($wechat->errMsg) ? $wechat->errMsg : '增加图文素材失败！');
        }
    }

    public function getArticle($media_id)
    {
        $wechat = new wxAction($this->wx_app_id);
        $result = $wechat->getForeverMedia($media_id);
        if ($result && isset($result['news_item']) && !empty($result['news_item'])) {
            return $result['news_item'];
        } else {
            return false;
        }
    }

    /**
     * 其他地方调用
     */
    public function actionArticleAddOther($articles)
    {
        $verJson = $this->verJson($articles);
        if (!$verJson['flag']) {
           return false;
        }

        $arrayDepth = $verJson['dep'];

        $orderRow = $verJson['list'];

        $orderNewItems = [];
        switch ((int) $arrayDepth) {
            case 1:
                $orderNewItems[] = [
                    'title' => $orderRow['title'],
                    'thumb_media_id' => $orderRow['thumb_media_id'],
                    'show_cover_pic' => $orderRow['show_cover_pic'],
                    'content' => $orderRow['content'],
                    'content_source_url' => $orderRow['content_source_url'],
                    'author' => $orderRow['author'],
                    'digest' => $orderRow['digest'],
                ];
                break;
            case 2:
                $orderNewItems = array_map(function ($item) {
                    return [
                        'title' => $item['title'],
                        'thumb_media_id' => $item['thumb_media_id'],
                        'show_cover_pic' => $item['show_cover_pic'],
                        'content' => $item['content'],
                        'content_source_url' => $item['content_source_url'],
                        'author' => $item['author'],
                        'digest' => $item['digest'],
                    ];
                }, $orderRow);
                break;
            default:
                return false;
        }

        //开始掺入数据库：
        $data = Cm::$db->one("SELECT id, news_start,news_sync_time FROM `scrm_weixin_fover_material` where wx_account_id='{$this->wx_account_id}' and `type`='news' order by add_time desc ");

        $start = 1;
        if ($data) {
            $start = (int)$data['news_start'];
        }

        $wechat=  new wxAction($this->wx_app_id);

        $item = [
            'articles'=>$orderNewItems
        ];
        $result = $wechat->uploadForeverArticles($item);
        if ($result) {
            $materialId = (new CreateUuid())->toString();
            $items = [
                'media_id'=>$result['media_id'],
                'id'=>$materialId,
                'wx_account_id'=>$this->wx_account_id,
                'add_time'=>date('Y-m-d H:i:s'),
                'update_time'=>date('Y-m-d H:i:s'),
                'type'=>'news',
                "news_start"=>$start,
                'title'=>'多图文',
                'media_id'=>$result['media_id'],
                //'url'=>$wechatResult['url'],
            ];
            Cm::$db->insert('scrm_weixin_fover_material', $items);

            $items = $this->getArticle($result['media_id']);
            $listItems = [];
            if ($items) {
                $listItems = $items;
            } else {
                $listItems = $orderNewItems;
            }
            if ($listItems) {
                foreach ($listItems as $v) {
                    $row = array_filter([
                        'id'=>(new CreateUuid())->toString(),
                        'material_id'=>$materialId,
                        'title'=>$v['title'],
                        'thumb_media_id'=>$v['thumb_media_id'],
                        'show_cover_pic'=>$v['show_cover_pic'],
                        'author'=>$v['author'],
                        'digest'=>$v['digest'],
                        'content'=>$v['content'],
                        'content_source_url'=>$v['content_source_url'],
                        'url'=>isset($v['url']) ? $v['url'] : '',
                        'thumb_url'=>isset($v['thumb_url']) ? $v['thumb_url'] : '',
                        'need_open_comment'=>isset($v['need_open_comment']) ? $v['need_open_comment'] : 0,
                        'only_fans_can_comment'=>isset($v['only_fans_can_comment']) ? $v['only_fans_can_comment'] : 0,
                        'update_time'=>date('Y-m-d H:i:s'),
                        'create_time'=>date('Y-m-d H:i:s'),

                    ]);
                    Cm::$db->insert('scrm_weixin_fover_material_items', $row);
                }
            }
            return [
                'media_id'=>$result['media_id'],
                'material_id'=>$materialId,
                'url'=>isset($listItems[0]['url']) ? $listItems[0]['url'] : '',
                'thumb_url'=>isset($listItems[0]['thumb_url']) ? $listItems[0]['thumb_url'] : '',
            ];
        } else {
            return false;
        }
    }

    /**
     * 修改素材
     */
    public function actionArticleUpd()
    {
        $id = Cm::$req->post('id', ['reg' => '/[a-z0-9A-z]+/', 'title' => '素材id']);
        $articles = Cm::$req->post('articles', ['reg' => '/[^,:{}\\[\\]0-9.\-+Eaeflnr-u \n\r\t]/', 'title' => '图文']);
        $verJson = $this->verJson($articles);
        if (!$verJson['flag']) {
            Cm::$res->error('无效json格式: 无效参数articles');
        }

        $arrayDepth = $verJson['dep'];

        $orderRow = $verJson['list'];

        $orderNewItems = [];
        switch ((int) $arrayDepth) {
            case 1:
                $orderNewItems[] = [
                    'title' => $orderRow['title'],
                    'thumb_media_id' => $orderRow['thumb_media_id'],
                    'show_cover_pic' => $orderRow['show_cover_pic'],
                    'content' => $orderRow['content'],
                    'content_source_url' => $orderRow['content_source_url'],
                    'author' => $orderRow['author'],
                    'digest' => $orderRow['digest'],
                ];
                break;
            case 2:
                $orderNewItems = array_map(function ($item) {
                    return [
                        'title' => $item['title'],
                        'thumb_media_id' => $item['thumb_media_id'],
                        'show_cover_pic' => $item['show_cover_pic'],
                        'content' => $item['content'],
                        'content_source_url' => $item['content_source_url'],
                        'author' => $item['author'],
                        'digest' => $item['digest'],
                    ];
                }, $orderRow);
                break;
            default:
                Cm::$res->error('无效json格式: 无效参数articles');
        }
        //查询素材：
        $result = Cm::$db->one("select media_id,id,type from `scrm_weixin_fover_material` where id='{$id}' and wx_account_id='{$this->wx_account_id}'");
        if (!$result) {
            Cm::$res->error('图文素材不存在！');
        }

        if (isset($result['type']) && $result['type']!='news') {
            Cm::$res->error('此素材非图文！');
        }

        $wechat=  new wxAction($this->wx_app_id);



        $item = [
            'articles'=>$orderNewItems
        ];
        $data = $wechat->updateForeverArticles($result['media_id'], $item);

        if ($data) {
            $materialId = (new CreateUuid())->toString();
            $itemsList = [
                'update_time'=>date('Y-m-d H:i:s'),
            ];
            Cm::$db->update('scrm_weixin_fover_material', $itemsList, "id='{$id}'");

            $items = $this->getArticle($result['media_id']);
            $listItems = [];
            if ($items) {
                $listItems = $items;
            } else {
                $listItems = $orderNewItems;
            }
            foreach ($listItems as $v) {
                $row = array_filter([
                    'title'=>$v['title'],
                    'thumb_media_id'=>$v['thumb_media_id'],
                    'show_cover_pic'=>$v['show_cover_pic'],
                    'author'=>$v['author'],
                    'digest'=>$v['digest'],
                    'content'=>$v['content'],
                    'content_source_url'=>$v['content_source_url'],
                    'url'=>isset($v['url']) ? $v['url'] : '',
                    'thumb_url'=>isset($v['thumb_url']) ? $v['thumb_url'] : '',
                    'need_open_comment'=>isset($v['need_open_comment']) ? $v['need_open_comment'] : 0,
                    'only_fans_can_comment'=>isset($v['only_fans_can_comment']) ? $v['only_fans_can_comment'] : 0,
                    'update_time'=>date('Y-m-d H:i:s'),
                ]);
                Cm::$db->update('scrm_weixin_fover_material_items', $row, "material_id='{$id}'");
            }
            Cm::$res->susess('success', ['id'=>$id, 'media_id'=>$result['media_id']]);
        } else {
            Cm::$res->error('修改失败');
        }


    }

    /**
     * 判断json是否符合标准
     * @param $items
     * @return array
     */
    private function verJson($items, $flag = false)
    {
        $itemsArray = json_decode($items, true);

        $arrayDepth = 1;
        $errorJson = true;
        if ($itemsArray) {
            $arrayDepth = self::array_depth($itemsArray);
            if ($arrayDepth > 1) {
                foreach ($itemsArray as $row) {
                    $key = array_keys($row);
                    if (!empty($key) && is_array($key)) {

                        if (!in_array('title', $key)) {
                            $errorJson = false;
                        }

                        if (!in_array('thumb_media_id', $key)) {
                            $errorJson = false;
                        }

                        if (!in_array('show_cover_pic', $key)) {
                            $errorJson = false;
                        }

                        if (!in_array('content', $key)) {
                            $errorJson = false;
                        }
                        if (!in_array('content_source_url', $key)) {
                            $errorJson = false;
                        }
                        if (!in_array('author', $key)) {
                            $errorJson = false;
                        }
                        if (!in_array('digest', $key)) {
                            $errorJson = false;
                        }
                        // if ($flag && !in_array('id', $key)) {
                        //     $errorJson=false;
                        // }

                    } else {
                        $errorJson = false;
                    }

                }
            } else {
                $key = array_keys($itemsArray);
                if (!empty($key) && is_array($key)) {

                    if (!in_array('title', $key)) {
                        $errorJson = false;
                    }

                    if (!in_array('thumb_media_id', $key)) {
                        $errorJson = false;
                    }

                    if (!in_array('show_cover_pic', $key)) {
                        $errorJson = false;
                    }

                    if (!in_array('content', $key)) {
                        $errorJson = false;
                    }
                    if (!in_array('content_source_url', $key)) {
                        $errorJson = false;
                    }
                    if (!in_array('author', $key)) {
                        $errorJson = false;
                    }
                    if (!in_array('digest', $key)) {
                        $errorJson = false;
                    }

                } else {
                    $errorJson = false;
                }
            }
        } else {
            $errorJson = false;
        }

        return [
            'flag' => $errorJson,
            'dep' => $arrayDepth,
            'list' => $itemsArray,
        ];
    }

    public function actionGroupingAdd()
    {
        $name = Cm::$req->post('name', ['title'=>'名称']);

        $result = Cm::$db->one("SELECT id FROM `scrm_weixin_fover_material_group` where wx_account_id='{$this->wx_account_id}' and `name`='{$name}'");
        if ($result) {
            Cm::$res->error('已存在分组名称！');
        }

        $id = (new CreateUuid())->toString();

        $data = [
            'name'=>$name,
            'id'=>$id,
            'wx_account_id'=>$this->wx_account_id,
            'company_id'=>$this->company_id,
            'add_time'=>date('Y-m-d H:i:s')
        ];
        Cm::$db->insert('scrm_weixin_fover_material_group', $data);

        Cm::$res->susess('创建成功！', [
            'group_id'=>$id,
            'name'=>$name
        ]);


    }
    public function actionGroupingDel()
    {
        $groupid = Cm::$req->post('group_id', ['reg'=>'/^[0-9A-Za-z]{1,}/', 'title'=>'分组id']);
        $result = Cm::$db->one("SELECT id FROM `scrm_weixin_fover_material_group` where id='{$groupid}'");
        if ($result) {

            $groups = Cm::$db->one("SELECT count(*) as num  FROM `scrm_weixin_fover_material` WHERE group_id='{$groupid}'");
            if ($groups && (int)$groups['num'] > 0) {
                Cm::$res->error('分组已归类图片，不允许删除');
            }
            Cm::$db->delete('scrm_weixin_fover_material_group', "id='{$groupid}'");

            Cm::$res->susess('删除成功！');
        } else {
            Cm::$res->error('分组不存在！');
        }
    }

    public function actionGroupingList()
    {
        $result = Cm::$db->all("SELECT id, `name`, add_time FROM `scrm_weixin_fover_material_group` where wx_account_id='{$this->wx_account_id}'");
        if (!$result) {
            $result = [];
        }

        Cm::$res->susess('success', $result);
    }
    public function actionGroupingUpd()
    {
        $name = Cm::$req->post('name', ['title'=>'名称']);
        $groupid = Cm::$req->post('group_id', ['reg'=>'/^[0-9A-Za-z]{1,}/', 'title'=>'分组id']);

        $result = Cm::$db->one("SELECT id FROM `scrm_weixin_fover_material_group` where id='{$groupid}'");
        if ($result) {

            $groups = Cm::$db->one("SELECT id FROM `scrm_weixin_fover_material_group` where wx_account_id='{$this->wx_account_id}' and `name`='{$name}'");

            if ($groups && $groups['id'] != $groupid) {
                Cm::$res->error('已存在分组名称！');
            }
            Cm::$db->update('scrm_weixin_fover_material_group', [
                'name'=>$name,
            ], "id='{$groupid}'");

            Cm::$res->susess('修改成功！', [
                'group_id'=>$groupid,
                'name'=>$name
            ]);
        } else {
            Cm::$res->error('分组不存在！');
        }
    }
    public function actionImgMoveGroup()
    {
        $groupid = Cm::$req->post('group_id', ['reg'=>'/^[0-9A-Za-z]{1,}/', 'title'=>'分组id']);
        $imgIds = Cm::$req->post('img_ids', ['reg'=>'/^[0-9A-Za-z]{1,}/', 'title'=>'图片id']);

        $result = Cm::$db->one("SELECT id FROM `scrm_weixin_fover_material_group` where id='{$groupid}'");
        if ($result) {

            $ids = explode(',', str_replace('，',',', $imgIds));

            $idsNew = implode(",", array_map(function( $v ){  return "'{$v}'";},$ids) );


            $upd = Cm::$db->update('scrm_weixin_fover_material', [
                'group_id'=>$groupid
            ], "wx_account_id='{$this->wx_account_id}' and id in ({$idsNew})");

            Cm::$res->susess('移动图片分组成功！', [
                'num'=>$upd ? $upd : 0
            ]);
        } else {
            Cm::$res->error('分组不存在！');
        }
    }

    /**
     * 图文消息
     */
    public function actionTempArticleList()
    {
        $key = Cm::$req->post('key',['title'=>'搜索关键词', 'null', 'empty']);
        $page = (int)Cm::$req->post('page',['reg'=>'/^\d+/', 'title'=>'分页']);
        $page_size = (int)Cm::$req->post('page_size',['reg'=>'/^\d+/', 'title'=>'素材个数', 'null','empty', 'default'=>'5']);

        $sql = "
        SELECT id,media_id,add_time,update_time
        FROM `scrm_weixin_fover_material`  
        WHERE wx_account_id='{$this->wx_account_id}' and `type`='news'";


        if (!empty($key)) {
            $result = Cm::$db->all("SELECT m.id
					FROM `scrm_weixin_fover_material` as m  
					inner JOIN scrm_weixin_fover_material_items as i on i.material_id=m.id
					WHERE m.wx_account_id='{$this->wx_account_id}' and m.`type`='news' and (i.title like '%{$key}%' or i.author like '%{$key}%'or i.digest like '%{$key}%')");
            if ($result) {
                $strId =implode(',',  array_map(function ($v){ return "'{$v}'";}, $this->_array_column($result, 'id')));
                $sql .= " AND id in ({$strId})";
            }
        }
        $sql .= " ORDER BY add_time desc ";
        $result = Cm::$db->paging($sql, $page, $page_size);

        if (isset($result['data']) && !empty($result['data']) && is_array($result['data'])) {

            $list = [];
            foreach ($result['data'] as $v) {
                $list[$v['id']] = $v;
            }


            $materialIds = implode(',',  array_map(function ($v){ return "'{$v}'";}, $this->_array_column($result['data'], 'id')));
            //$materialIds = implode(',',  $this->_array_column($result['data'], 'id'));
            $itemsSql = "
            SELECT id,material_id, title,thumb_media_id,url, thumb_url, author,
            digest,show_cover_pic,content,content_source_url,update_time,create_time 
            FROM `scrm_weixin_fover_material_items` 
            WHERE material_id in ({$materialIds}) ";


//            if (!empty($key)) {
//                $sql = " and (title like '%{$key}%' or author like '%{$key}%'or digest like '%{$key}%')";
//            }
            $items = Cm::$db->all($itemsSql);
            if ($items && is_array($items) && !empty($items)) {
                foreach ($items as $item) {
                    $k = $item['material_id'];

                    if (isset($list[$k])) {
                        if (isset($list[$k]['items']) && !empty($list[$k]['items'])) {
                            array_push($list[$k]['items'], $item);
                        } else {
                            $list[$k]['items'][] = $item;
                        }
                    }
                }
            }
            $result['data'] = array_values($list);
        }

        $result['wx_account_id'] = $this->wx_account_id;
        $result['appid'] = $this->wx_app_id;
        $result['company_id'] = $this->company_id;
        //$result['type'] = $type;

        Cm::$res->susess('success', $result);
    }
}